//
//  PutInProductViewController.m
//  quickBatchManager
//
//  Created by 王定波 on 15/9/15.
//  Copyright (c) 2015年 jack. All rights reserved.
//

#import "PutInProductViewController.h"

@interface PutInProductViewController ()<UITextFieldDelegate>
{
    UIPopoverController *popover;
    NSArray *colorList;
    NSArray *sizeList;
    UILabel *totalLabel;
    NSMutableArray *proList;
    PMCalendarController *pmCC;
    AAMenuBubbles *payMenu;
    ChooseProductController *menuprocuctVc;
    UIPopoverController *cppopover;
    NSString *picpath;
    CategoryModel *category;
}

@end

@implementation PutInProductViewController
@synthesize batch;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


-(void)initUI
{
    [super initUI];
    [self addNavBack];
    self.title=@"到货";
    _tableView.backgroundColor=[UIColor clearColor];
    [_dateBtn setTitle:[NSString stringWithFormat:@"%@",[[NSDate date] dateStringWithFormat:@"yyyy.MM.dd"]] forState:UIControlStateNormal];
    
    
    _tableView.tableFooterView = [[UIView alloc]init];
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [_tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    
    
    
    
    [self initAddUI];
    [self reloadTableView];
    [self reloadData];
    
}


-(void)reloadData
{
    SupplierModel *sp=[AppService getSupplyByBatchNo:batch.batchNo];
    category=nil;
    if(sp)
    {
        _supplierLabel.text=sp.contactName;
    }
    else _supplierLabel.text=@"";
    
    if(batch.isPay==1)
    {
        [_yzBtn setTitle:batch.payType forState:UIControlStateNormal];
        [_payBtn setSelected:YES];
         _yzBtn.hidden=NO;
    }
    else
    {
         [_payBtn setSelected:NO];
         _yzBtn.hidden=YES;
    }
    
    
}

-(void)initData
{
    if(!batch)
    batch=[AppService getBatchProductByDate:nil];
    _piciLable.text=[NSString stringWithFormat:@"批次：%@",batch.batchNo];
    proList=[[NSMutableArray alloc] init];
}


-(void)initAddUI
{
    
    
    [_payBtn bk_whenTapped:^{
        
        if(!_payBtn.isSelected)
        {
            if(payMenu) {
                payMenu = nil;
            }
            payMenu = [[AAMenuBubbles alloc] initWithPoint:_payBtn.center radius:90 andBubbles:[[NSString stringWithFormat:@"%@%@",[CoreArchive strForKey:NSDEFAULT_ST_PAYMENT],[CoreArchive boolForKey:NSDEFAULT_ST_PAYMENT_DS ]?@"|代收":@""] componentsSeparatedByString:@"|"] inView:self.view];
            payMenu.bubbleRadius = 30;
            payMenu.delegate=self;
            [payMenu show];
        }
        else
        {
            batch.isPay=0;
            batch.payType=@"";
            [batch updateToDB];
            [_payBtn setSelected:NO];
            _yzBtn.hidden=YES;
        }
        
       
    }];
    _photoImageView.hidden=YES;
    [_closeBtn bk_whenTapped:^{
        [self back];
    }];
    
    [_photoBtn bk_whenTapped:^{
        [self pickPhoto];
    }];
    
    [_cameraBtn bk_whenTapped:^{
        [self pickCamera];
    }];
    
    
    [_dateBtn bk_whenTapped:^{
        pmCC = [[PMCalendarController alloc] initWithThemeName:@"default"];
        pmCC.delegate = self;
        pmCC.mondayFirstDayOfWeek = NO;
        if ([pmCC isCalendarVisible])
        {
            [pmCC dismissCalendarAnimated:NO];
        }
        [pmCC presentCalendarFromView:_dateBtn
                  permittedArrowDirections:PMCalendarArrowDirectionAny
                                 isPopover:YES
                                  animated:YES];
        pmCC.period = [PMPeriod oneDayPeriodWithDate:[NSDate date]];
    }];
    
    [_sizeBtn bk_whenTapped:^{
        AddSizeViewController *vc=[[AddSizeViewController alloc] init];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        self.definesPresentationContext = YES;
        vc.delegate=self;
        [self presentViewController:vc animated:YES completion:nil];
    }];
    
    
    [_colorBtn bk_whenTapped:^{
        AddColorViewController *vc=[[AddColorViewController alloc] init];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        self.definesPresentationContext = YES;
        vc.delegate=self;
        [self presentViewController:vc animated:YES completion:nil];
    }];
    
    
    [_tsczBtn bk_whenTapped:^{
       
        
        TsczViewController *vc=[[TsczViewController alloc] init];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        vc.batchNo=batch.batchNo;
        vc.type = TsczBatch;
        self.definesPresentationContext = YES;
        [self presentViewController:vc animated:YES completion:nil];
    }];
    
    [_supplierBtn bk_whenTapped:^{
        
        ChooseSupplierViewController *vc=[[ChooseSupplierViewController alloc] init];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        self.definesPresentationContext = YES;
        vc.delegate=self;
        UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:vc];
        nav.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        nav.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        nav.view.backgroundColor=[UIColor clearColor];
        [self presentViewController:nav animated:YES completion:nil];
    }];
    
    
    [_categoryBtn bk_whenTapped:^{
        ChooseCategoryController *menuVc=[[ChooseCategoryController alloc]init];
        menuVc.delegate=self;
        popover=[[UIPopoverController alloc]initWithContentViewController:menuVc];
        popover.popoverContentSize=CGSizeMake(200, 300);
        [popover presentPopoverFromRect:CGRectMake(40, 20, 10, 10) inView:_categoryBtn permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        
        [menuVc.addBtn bk_whenTapped:^{
            [popover dismissPopoverAnimated:YES];
            AddCategoryViewController *vc=[[AddCategoryViewController alloc] init];
            vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
            self.definesPresentationContext = YES;
            vc.delegate = menuVc;
            [self presentViewController:vc animated:YES completion:nil];
        }];
    }];
    
    _modelNumberField.tag=101;
    [self addTextFieldChange:_modelNumberField];
    
    
    //产品弹出层
    menuprocuctVc=[[ChooseProductController alloc]init];
    menuprocuctVc.delegate=self;
    cppopover=[[UIPopoverController alloc]initWithContentViewController:menuprocuctVc];
    cppopover.popoverContentSize=CGSizeMake(200, 300);
    
    
    
    
    
    [_addBtn bk_whenTapped:^{
        if([_categoryBtn.titleLabel.text isEqualToString:@"选择分类"])
        {
            [self showAlert:@"请设置分类"];
            return ;
        }
        
        
        if([_modelNumberField.text isBlank])
        {
            [self showAlert:@"型号必须填写"];
            return ;
        }
        
        if([_inPriceField.text isBlank])
        {
            [self showAlert:@"进价必须填写"];
            return ;
        }
        
        if([_outPriceField.text isBlank])
        {
            [self showAlert:@"售价必须填写"];
            return ;
        }
        
        if(sizeList.count==0)
        {
            [self showAlert:@"尺码必须填写"];
            return ;
        }
        
        if(colorList.count==0)
        {
            [self showAlert:@"颜色必须填写"];
            return ;
        }
        
        
        
        if(![_colorSizeView checkInput:YES])
        {
            [self showAlert:@"数量必须填写"];
            return ;
        }

        
        
        batch=[AppService putInProduct:_modelNumberField.text andBatch:batch andCategory:category andBuyPrice:_inPriceField.text andSalePrice:_outPriceField.text andImage:_photoImageView.image andPicPath:picpath andColorSizeView:_colorSizeView];
        batch.remark = _remarkField.text;
        [self showAlert:@"添加成功" handler:^{
            [self reloadUI];
        }];
    }];
    
    
    [_overBatchBtn bk_whenTapped:^{
        
        if(proList.count>0)
        {
            UIAlertView *alert=[UIAlertView bk_alertViewWithTitle:@"提示" message:@"确定结束批次？"];
            [alert bk_setCancelButtonWithTitle:@"取消" handler:^{
                
            }];
            
            [alert bk_addButtonWithTitle:@"确定" handler:^{
                [AppService overBatchProduct:batch];
                [self back];
            }];
            
            [alert show];
        }
        else [self showAlert:@"请添加产品"];
        
        
    }];
}


-(void) reloadUI
{
    _photoImageView.image=[UIImage imageNamed:@""];
    [_categoryBtn setTitle:@"选择分类" forState:UIControlStateNormal];
    _modelNumberField.text=@"";
    _inPriceField.text=@"";
    _outPriceField.text=@"";
    sizeList=[NSArray new];
    colorList=[NSArray new];
    picpath=@"";
    
    
    [self didSelectDatas:ChooseTypeColor andData:[NSArray new]];
    
    [self didSelectDatas:ChooseTypeSize andData:[NSArray new]];
    [self reloadTableView];
    
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [super imagePickerController:picker didFinishPickingMediaWithInfo:info];
    _photoImageView.hidden=NO;
    UIImage * photo =[ToolUtils scaleToSize:(UIImage*)[info objectForKey:UIImagePickerControllerOriginalImage]];
    _photoImageView.image=photo;
    picpath=@"";
    
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 40;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return proList.count;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *reuseIdetify = @"ProductViewCell";
    ProductViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdetify];
    ProductModel *data=[proList objectAtIndex:indexPath.row];
    if(!cell){
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"ProductViewCell" owner:self options:nil];
        for(id oneObject in nib){
            if([oneObject isKindOfClass:[ProductViewCell class]]){
                cell = (ProductViewCell *) oneObject;
                
            }
        }
        
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.backgroundColor=[UIColor clearColor];
    
    cell.modelLabel.text=data.modelNo;
    cell.priceLabel.text=[NSString stringWithFormat:@"%0.2f",data.buyPrice];
    
    cell.countLabel.text=[NSString stringWithFormat:@"%0.0f",data.totalNumber];
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])  {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
    
    return cell;
    
    
}


#pragma -ChooseDelegate 
-(void)didSelectDatas:(ChooseType)type andData:(NSArray *)selectDatas
{
    UIColor *bg=[UIColor colorWithWhite:0.89 alpha:1];
    UIColor *textcolor=[UIColor colorWithWhite:0.49 alpha:1];
     UIColor *bordercolor=[UIColor colorWithRed:0.73 green:0.68 blue:0.69 alpha:1];
    switch (type) {
        case ChooseTypeSize:
            for (UIView *view in _sizeView.subviews) {
                [view removeFromSuperview];
            }
            int sy=0;
            for (NSString *size in selectDatas) {
                UILabel *sizeLabel=[[UILabel alloc] initWithFrame:CGRectMake(sy, 5, 20, 30)];
                sizeLabel.text=size;
                sizeLabel.textAlignment=NSTextAlignmentCenter;
                sizeLabel.font=[UIFont systemFontOfSize:15];
                sizeLabel.textColor=textcolor;
                sizeLabel.backgroundColor=bg;
                sizeLabel.layer.cornerRadius=4;
                sizeLabel.clipsToBounds=YES;
                sizeLabel.layer.borderWidth=1;
                sizeLabel.layer.borderColor=bordercolor.CGColor;
                [sizeLabel sizeToFit];
                sizeLabel.frame=CGRectMake(sy, 5, sizeLabel.frame.size.width+10, 30);
                sy=CGRectGetMaxX(sizeLabel.frame)+10;
                [_sizeView addSubview:sizeLabel];
            }
            
            
            for (NSLayoutConstraint *ct in  [_sizeView constraints]) {
                if(ct.firstAttribute==NSLayoutAttributeWidth)
                {
                    ct.constant=sy;
                }
            }
            sizeList=selectDatas;
            
            
            [self reloadNumber];
            break;
        case ChooseTypeColor:
            for (UIView *view in _colorView.subviews) {
                [view removeFromSuperview];
            }
            int cy=0;
            for (NSString *size in selectDatas) {
                UILabel *sizeLabel=[[UILabel alloc] initWithFrame:CGRectMake(cy, 5, 20, 30)];
                sizeLabel.text=size;
                sizeLabel.textAlignment=NSTextAlignmentCenter;
                sizeLabel.font=[UIFont systemFontOfSize:15];
                sizeLabel.textColor=textcolor;
                sizeLabel.backgroundColor=bg;
                sizeLabel.layer.cornerRadius=4;
                sizeLabel.clipsToBounds=YES;
                sizeLabel.layer.borderWidth=1;
                sizeLabel.layer.borderColor=bordercolor.CGColor;
                [sizeLabel sizeToFit];
                sizeLabel.frame=CGRectMake(cy, 5, sizeLabel.frame.size.width+10, 30);
                cy=CGRectGetMaxX(sizeLabel.frame)+10;
                [_colorView addSubview:sizeLabel];
            }
            
            
            for (NSLayoutConstraint *ct in  [_colorView constraints]) {
                if(ct.firstAttribute==NSLayoutAttributeWidth)
                {
                    ct.constant=cy;
                }
            }
            
            colorList=selectDatas;
            
            [self reloadNumber];
            break;
            
        default:
            break;
    }
}

-(void)didSelectData:(ChooseType)type andData:(id)selectData
{
   
    if(type==ChooseTypeCategory)
    {
        category=(CategoryModel*)selectData;
        [_categoryBtn setTitle:category.categoryName forState:UIControlStateNormal];
        [popover dismissPopoverAnimated:YES];
    }
   else if(type==ChooseTypeSupplier)
    {
         SupplierModel *data=(SupplierModel*)selectData;
         _supplierLabel.text=data.contactName;
        
         batch.supplierId=data.supplierId;
        [batch updateToDB];
        
    }
    
   else if(type==ChooseTypeProduct)
   {
       ProductModel *data=(ProductModel*)selectData;
       NSDictionary *dic=[AppService getSizeAndColorByModel:data.modelNo];
       [self reloadUI];
       [self didSelectDatas:ChooseTypeColor andData:[dic objectForKey:@"color"]];
       [self didSelectDatas:ChooseTypeSize andData:[dic objectForKey:@"size"]];
       
       
       _modelNumberField.text=data.modelNo;
       if(![data.photo isBlank])
       {
           _photoImageView.image=[UIImage imageWithData:[NSData dataWithContentsOfFile:[ToolUtils getImageLocalPath:data.photo]]];
           _photoImageView.hidden=NO;
           picpath=data.photo;
       }
       
       _inPriceField.text=[ToolUtils priceToStr:data.buyPrice];
       _outPriceField.text=[ToolUtils priceToStr:data.salePrice];
        category=data.category;
       [_categoryBtn setTitle:category.categoryName forState:UIControlStateNormal];
       
       
       [_modelNumberField resignFirstResponder];
       [cppopover dismissPopoverAnimated:YES];
   }

}


-(void) reloadNumber
{
    [_colorSizeView setColorList:colorList];
    [_colorSizeView setSizeList:sizeList];
}

-(void)textFieldChanged:(id)sender
{
    UITextField *text=(UITextField*)sender;
    
    if(text.tag==101)
    {
       NSArray *psroList=[AppService searchProductByKeyWord:text.text];
        
        if(psroList.count>0 && ![text.text isBlank])
        {
            [cppopover presentPopoverFromRect:CGRectMake(40, 20, 10, 10) inView:_modelNumberField permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
            [menuprocuctVc setDataList:psroList];
        }
        else
        {
            [cppopover dismissPopoverAnimated:YES];
        }
            
        
        
        
    }
    
}

-(void) reloadTableView
{
    NSArray *aplist=[AddProductModel searchWithWhere:@{@"batchId":[ToolUtils numberToStr:batch.batchId]} orderBy:@"batchId Desc" groupBy:@"productId" offset:0 count:0];
    [proList removeAllObjects];
    double totalCount=0;
    double totalAmount=0;
    for (AddProductModel *data in aplist) {
        data.product.totalNumber=[AddProductModel sumWithWhere:@"productNumber" where:@{@"productId":[ToolUtils numberToStr:data.productId],@"batchId":[ToolUtils numberToStr:batch.batchId]}];
        [proList addObject:data.product];
        
        totalCount+=data.productNumber;
        totalAmount+=data.productNumber*data.buyPrice;
    }
    
    
    
    _totalCountLabel.text=[NSString stringWithFormat:@"共%.0f件",totalCount];
    _totalAmountLabel.text=[NSString stringWithFormat:@"%.2f",totalAmount];
    
    [_tableView reloadData];
}

#pragma mark PMCalendarControllerDelegate methods

- (void)calendarController:(PMCalendarController *)calendarController didChangePeriod:(PMPeriod *)newPeriod
{
    [_dateBtn setTitle:[NSString stringWithFormat:@"%@",[newPeriod.startDate dateStringWithFormat:@"yyyy.MM.dd"]] forState:UIControlStateNormal];
   // [pmCC dismissCalendarAnimated:YES];
    
}

#pragma mark-AAMenuBubblesDelegate
-(void)AAMenuBubbles:(AAMenuBubbles *)shareBubbles andIndex:(int)index
{
    [_yzBtn setTitle:payMenu.bubblestrs[index] forState:UIControlStateNormal];
    [_payBtn setSelected:YES];
    _yzBtn.hidden=NO;
    batch.isPay=1;
    batch.paidPrice = batch.totalPrice;
    batch.payType=payMenu.bubblestrs[index];
    [batch updateToDB];
}



@end
